package com.xxxx.controller;

import com.xxxx.entity.User;
import com.xxxx.entity.vo.MessageModel;
import com.xxxx.service.UserService;
import com.xxxx.util.StringUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/register")
public class RegisterServlet extends HttpServlet {
    private UserService userService = new UserService();

    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String userName = req.getParameter("uname");
        String userPwd = req.getParameter("upwd");
        String confirmPwd = req.getParameter("upwd2");

        // 参数校验
        MessageModel messageModel = StringUtil.checkRegisterParams(userName, userPwd, confirmPwd);
        if (messageModel.getCode() != 1) {
            req.setAttribute("message", messageModel.getMsg());
            req.getRequestDispatcher("register.jsp").forward(req, resp);
            return;
        }

        // 直接使用明文密码
        User user = new User();
        user.setUsername(userName);
        user.setPassword(userPwd); // 去除了加密步骤

        messageModel = userService.registerUser(user);

        if (messageModel.getCode() == 1) {
            resp.sendRedirect("./login.jsp");
        } else {
            req.setAttribute("message", messageModel.getMsg());
            req.getRequestDispatcher("register.jsp").forward(req, resp);
        }
    }
}